import mongoose from 'mongoose'
import glob from 'glob'
import {resolve} from 'path'
import config from './../config/index.js'
mongoose.Promise=global.Promise
var env=process.env.NODE_ENV||'development'
var db=config.dbOnline
if(env=='development'){
     db=config.dbLocalhost
}
const initSchema=()=>{
    glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require)
}

const initAdmin=async ()=>{
    const User=mongoose.model('User')
    let user=await User.findOne({
        username:'suqian'
    })
    if(!user){
        const user=new User({
            username:'suqian',
            email:'401097366@qq.com',
            password:'123abc',
            role:'admin'
        })
        await user.save()
    }
    const Movie=mongoose.model('Movie')
    await Movie.remove({
      coverKey:{$exists:false}
    })
}
const connect=async()=>{
    let maxConnectTimes=0;
   return new Promise((resolve,reject)=>{
     //  console.log(process.env.NODE_ENV)
       if(env!=='production'){
           mongoose.set('debug',true)
       }
        mongoose.connect(db)

    mongoose.connection.on('disconnected',()=>{
        maxConnectTimes++
        if(maxConnectTimes<5){
            mongoose.connect(db)
        }else{
            throw new Error("数据库已经挂了，快去修吧")
        }
     
    })
    mongoose.connection.on('error',()=>{
        maxConnectTimes++
        if(maxConnectTimes<5){
            mongoose.connect(db)
        }else{
            throw new Error("数据库已经挂了，快去修吧")
        }
    })
    mongoose.connection.once('open',()=>{
 
        resolve()
        console.log("数据库成功启动。。。")
    })
   })
}
console.log(db)
export default{
    initSchema,
    connect,
    initAdmin
    
}
